package com.mccken.demo.io.buffer;

import java.nio.ByteBuffer;

import static com.mccken.demo.io.util.ByteBufferUtil.debugAll;

/**
 * Created by lilinchao
 * Date 2022/5/25
 * Description bytebuffer读写示例
 */
public class TestByteBufferReadWrite {
	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(10);
		buffer.put((byte) 0x61);    //a
		debugAll(buffer);
		buffer.put(new byte[]{0x62, 0x63, 0x64}); //b、c、d
		debugAll(buffer);
		//flip:切换对缓冲区的操作模式 写模式 --> 读模式
		buffer.flip();
		System.out.println(buffer.get());
		//get(i):不会改变索引的位置
		System.out.println(buffer.get(2));
		debugAll(buffer);
		//compact:会把未读完的数据向前压缩，然后切换到写模式
		buffer.compact();
		debugAll(buffer);
		buffer.put(new byte[]{0x65, 0x6f});
		debugAll(buffer);
		// rewind 从头开始读
		buffer.flip();
		System.out.println((char) buffer.get());
		System.out.println((char) buffer.get());
		buffer.rewind();
		System.out.println((char) buffer.get());
	}

}